<template>
  <div>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <Authority value="btn:dept:add">
          <a-button color="success" @click="handleCreate" style="margin-right: 10px">
            新增部门
          </a-button>
        </Authority>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑部门',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除？',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DeptModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script setup lang="ts">
  import { nextTick } from 'vue';
  import { Authority } from '@/components/Authority';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getDeptList, delDepartment } from '@/api/system/department';

  import { useModal } from '@/components/Modal';
  import DeptModal from './DeptModal.vue';

  import { columns, searchFormSchema } from './dept.data';
  import { useMessage } from '@/hooks/web/useMessage';

  defineOptions({ name: 'DeptManagement' });

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, expandAll }] = useTable({
    title: '部门管理',
    api: getDeptList,
    columns,
    formConfig: {
      labelWidth: 40,
      schemas: searchFormSchema,
    },
    isTreeTable: true,
    pagination: false,
    striped: false,
    useSearchForm: false,
    bordered: true,
    showIndexColumn: false,
    size: 'small',
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: undefined,
    },
  });

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    console.log(record);
    try {
      const { code, result, message } = await delDepartment(record['id']);
      console.log(code, result, message);
      if (code != 0) {
        createMessage.error(message);
      } else {
        createMessage.success('删除成功');
        reload();
      }
    } catch (err) {
      console.log(err);
    }
  }

  function handleSuccess() {
    reload();
  }

  function onFetchSuccess() {
    // 演示默认展开所有表项 expandAll
    nextTick(expandAll);
  }
</script>
